<template>
    <div style="background-color: #ececec; padding: 20px">
      <a-row :gutter="15">
        <a-col>
          <a-card title="用水量统计" :bordered="false">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
              <el-form-item label="起始时间:">
                <el-date-picker v-model="formInline.startTime" :type="formInline.datePickerType" placeholder="选择起始时间"></el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间:">
                <el-date-picker v-model="formInline.endTime" :type="formInline.datePickerType" placeholder="选择结束时间"></el-date-picker>
              </el-form-item>
              <el-form-item label="部门:">
                <el-select v-model="formInline.dept" placeholder="选择部门">
                  <el-option v-for="item in this.dept"
                          :key="item.value"
                          :label="item.label"
                          :value="item.departName">{{ item.departName }}
                        </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="日期类型:">
                <el-select v-model="formInline.datePickerType" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </el-form-item>
            </el-form>
          </a-card>
        </a-col>
      </a-row>
      
      <a-row :gutter="16" :style="{ marginTop: '16px' }">
        <a-col :span="6">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>本月累计用水(t)</span>
            </div>
            <div class="text item" style="font-size: 44px;">{{thisMonth}}</div>
          </el-card>
        </a-col>
        <a-col :span="6">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>今年用水量峰值(t)</span>
            </div>
            <div class="text item" style="font-size: 44px;">{{yearMax}}</div>
          </el-card>
        </a-col>
        <a-col :span="6">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>今年用水量最小值(t)</span>
            </div>
            <div class="text item" style="font-size: 44px;">{{yearMin}}</div>
          </el-card>
        </a-col>
        <a-col :span="6">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>今年平均用水量(t)</span>
            </div>
            <div class="text item" style="font-size: 44px;">{{yearAvg}}</div>
          </el-card>
        </a-col>
      </a-row>
      <br>

      <a-row :gutter="16" :style="{ marginTop: '16px' }">
        <a-col :span="7">
          <a-card title="水耗用"   :bordered="false">
            <div style="width:100%; height:330px;">
              <div id="water1" class="five"></div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="17">
          <a-card title="各部门用水情况" :bordered="false">
            <div style="width:100%; height:330px;">
              <div id="water2" class="five"></div>
            </div>
          </a-card>
        </a-col>
      </a-row>
      <br>

      <template>
        <a-card style="width: 100%">
          <div style="width:100%; height:330px;">
            <div id="water3" class="five"></div>
          </div>
        </a-card>
      </template>

    </div>
  </template>

<script>
import { httpAction, getAction, postAction } from '@/api/manage'
import * as echarts from 'echarts';
  function addTwoArr(arr1, arr2) {
    if (arr1.length === 0 && arr2.length === 0) {
      return []; // 如果arr1和arr2均为空数组，则返回一个空数组
    } else if (arr1.length === 0) {
      return arr2; // 如果arr1为空数组，返回arr2
    } else if (arr2.length === 0) {
      return arr1; // 如果arr2为空数组，返回arr1
    }
    const minLength = Math.min(arr1.length, arr2.length);
    const arr3 = [];
    for (let i = 0; i < minLength; i++) {
      arr3[i] = arr1[i] + arr2[i];
    }
    // 如果arr1和arr2长度不一致，将剩余部分添加到arr3
    if (arr1.length > arr2.length) {
      arr3.push(...arr1.slice(minLength));
    } else if (arr2.length > arr1.length) {
      arr3.push(...arr2.slice(minLength));
    }
    return arr3;
  }

  export default {
    data () {
      return {
        options: [{value: 'month', label: '月'}, {value: 'date', label: '天'}],
        chart1: null,
        chart2: null,
        chart3: null,
        formInline: {
          startTime: '',
          endTime: '',
          dept: '',
          datePickerType: 'month',
        },
        dept:[],
        water1:[],
        water2:[],
        recycled1:[],
        recycled2:[],
        waterByDept1:[],
        waterByDept2:[],
        recycledByDept1:[],
        recycledByDept2:[],
        allWater:'',
        allRecycled:'',
        thisMonthWater: '',
        thisMonthRecycled: '',
        thisMonth: '',
        yearMax: '',
        yearMin: '',
        yearAvgWater: '',
        yearAvgRecycled: '',
        yearAvg: '',
        url: {
          getDept: '/sys/sysDepart/list',
          getWaterStatistics:'/consumptionWater/consumptionWater/select',
          getRecycledStatistics:'/consumptionRecycledwater/consumptionRecycledwater/select',
          getWater: '/consumptionWater/consumptionWater/getAll',
          getRecycledWater: '/consumptionRecycledwater/consumptionRecycledwater/getAll',
          getWaterByDpet: '/consumptionWater/consumptionWater/getAllGroupByDept',
          getRecycledByDpet: '/consumptionRecycledwater/consumptionRecycledwater/getAllGroupByDept',
        },
      }
    },
    methods: {
      loadWaterAndRecycled(){
        getAction(this.url.getWater).then((res)=>{
          this.allWater = res.result;
        });
        getAction(this.url.getRecycledWater).then((res)=>{
          this.allRecycled = res.result;
        })
      },
      getWaterByDpet(){
        let waterByDept1 = [];
        let waterByDept2 = [];
        getAction(this.url.getWaterByDpet).then((res)=>{
          console.log(res);
          res.result.forEach(item=>{
            waterByDept1.push(item.dept);
            waterByDept2.push(item.sum_value);
          })
          this.waterByDept1 = waterByDept1;
          this.waterByDept2 = waterByDept2;
        });
      },
      getRecycledByDpet(){
        let recycledByDept1 = [];
        let recycledByDept2 = [];
        getAction(this.url.getRecycledByDpet).then((res)=>{
          console.log(res);
          res.result.forEach(item=>{
            recycledByDept1.push(item.dept);
            recycledByDept2.push(item.sum_value);
          })
          this.recycledByDept1 = recycledByDept1;
          this.recycledByDept2 = recycledByDept2;
        });
      },
      loadWater(){
        var endDate = new Date();
        var startDate = (endDate.getFullYear()-1)+"/"+(endDate.getMonth()+1);
        let year = endDate.getFullYear();
        let month = endDate.getMonth()+1;
        let water1 = [];
        let water2 = [];
        let recycled2 = [];
        let thisMonthWater = 0;
        let thisMonthRecycled = 0;
        let yearAvgWater = 0;
        let yearAvgRecycled = 0;
        this.formInline.startTime = new Date(Date.parse(startDate));
        this.formInline.endTime = endDate;
        postAction(this.url.getWaterStatistics,this.formInline).then((res)=>{
          console.log(res)
          res.result.forEach(e=>{
            let con = parseInt(e.consumption);
            if(month == e.month && year == e.year){
              thisMonthWater += con;
            }
            if (year == e.year){
              yearAvgWater += con;
            }
            if('date' == this.formInline.datePickerType){
              water1.push(e.year+'-'+e.month+'-'+e.day);
            }else{
              water1.push(e.year+'-'+e.month);
            }
            water2.push(con);
          })
          this.water1 = water1;
          this.water2 = water2;
          this.thisMonthWater = thisMonthWater;
          this.yearAvgWater = Math.trunc(yearAvgWater/month);
        })
        postAction(this.url.getRecycledStatistics,this.formInline).then((res)=>{
          console.log(res)
          res.result.forEach(e=>{
            let con = parseInt(e.consumption);
            if(month == e.month && year == e.year){
              thisMonthRecycled += con;
            }
            if (year == e.year){
              yearAvgRecycled += con;
            }
            recycled2.push(con);
          })
          this.recycled2 = recycled2;
          this.thisMonthRecycled = thisMonthRecycled;
          this.yearAvgRecycled = Math.trunc(yearAvgRecycled/month);
        })
      },
      onSubmit() {
        var endDate = new Date();
        let year = endDate.getFullYear();
        let month = endDate.getMonth()+1;
        let water1 = [];
        let water2 = [];
        let recycled2 = [];
        let thisMonthWater = 0;
        let thisMonthRecycled = 0;
        let yearAvgWater = 0;
        let yearAvgRecycled = 0;
        if('month' == this.formInline.datePickerType){
          let endTime = new Date(this.formInline.endTime);
          let year = endTime.getFullYear();
          let month = endTime.getMonth()+1;
          let lastDate = new Date(year, month , 0).getDate();
          month = month < 10 ? '0' + month : month ;
          endTime = [year,month ,lastDate ].join("-")+" 23:59:59";
          this.formInline.endTime = new Date(endTime);
        }
        postAction(this.url.getWaterStatistics,this.formInline).then((res)=>{
          console.log(res)
          res.result.forEach(e=>{
            let con = parseInt(e.consumption);
            if(month == e.month && year == e.year){
              thisMonthWater += con;
            }
            if (year == e.year){
              yearAvgWater += con;
            }
            if('date' == this.formInline.datePickerType){
              water1.push(e.year+'-'+e.month+'-'+e.day);
            }else{
              water1.push(e.year+'-'+e.month);
            }
            water2.push(con);
          })
          this.water1 = water1;
          this.water2 = water2;
          this.thisMonthWater = thisMonthWater;
          this.yearAvgWater = Math.trunc(yearAvgWater/month);
        })
        postAction(this.url.getRecycledStatistics,this.formInline).then((res)=>{
          console.log(res)
          res.result.forEach(e=>{
            let con = parseInt(e.consumption);
            if(month == e.month && year == e.year){
              thisMonthRecycled += con;
            }
            if (year == e.year){
              yearAvgRecycled += con;
            }
            recycled2.push(con);
          })
          this.recycled2 = recycled2;
          this.thisMonthRecycled = thisMonthRecycled;
          this.yearAvgRecycled = Math.trunc(yearAvgRecycled/month);
        })
        setTimeout(() => {
          this.thisMonth = this.thisMonthWater + this.thisMonthRecycled;
          this.yearAvg = this.yearAvgWater + this.yearAvgRecycled;
          this.yearMax = Math.max.apply(null,addTwoArr(this.water2, this.recycled2));
          this.yearMin = Math.min.apply(null,addTwoArr(this.water2, this.recycled2));
          this.getzhu();
        }, 500)
      },
      handleChange1(){
        this.dept = []
        getAction(this.url.getDept).then((res)=>{
          this.dept = res.result;
        })
      },
      getbing(){
        if(this.chart1 != null && this.chart1 != '' && this.chart1 != undefined){
          this.chart1.dispose();
        }
        var chartDom = document.getElementById('water1');
        this.chart1 = echarts.init(chartDom);
        var option;
        option = {
          title: {},
          tooltip: {},
          legend: {data: ['自来水','中水']},
          toolbox: {padding: [0,15,0,0]},
          label: {show: false},
          labelLine: {show: false},
          series: [
            {
              name: '水耗用',
              data: [{name: '自来水', value: this.allWater},
                    {name: '中水', value: this.allRecycled}],
              type: 'pie'
            }
          ],
        };
        option && this.chart1.setOption(option,true);
      },
      getzhe(){
        if(this.chart2 != null && this.chart2 != '' && this.chart2 != undefined){
          this.chart2.dispose();
        }
        var chartDom = document.getElementById('water2');
        this.chart2 = echarts.init(chartDom);
        var option;
        option = {
          title: {},
          tooltip: {trigger: 'axis', axisPointer: {type: 'shadow'}},
          legend: {
            data: ['自来水用水量','中水用水量']
          },
          toolbox: {
            feature: {
              dataView: {show: true, readOnly: false},
              magicType: {show: true, type: ['line', 'bar']},
              restore: {show: true},
              saveAsImage: {show: true}
            },
            padding: [0,15,0,0]
          },
          xAxis: [
            {type: 'category', data: this.waterByDept1,},
          ],
          yAxis: [
            {type: 'value', name: 't'},
          ],
          series: [
            {name: '自来水用水量', data: this.waterByDept2, stack: "Search Engine", type: 'bar'},
            {name: '中水用水量', data: this.recycledByDept2, stack: "Search Engine", type: 'bar'},
            {
            name: '总计',
              type: 'line',
              lineStyle: {
                  opacity: 0,
              },
              symbolSize:0,
              data: addTwoArr(this.recycledByDept2, this.waterByDept2)
            }
          ],
        };
        option && this.chart2.setOption(option,true);
      },
      getzhu(){
        var chartDom = document.getElementById('water3');
        if(this.chart3 != null && this.chart3 != '' && this.chart3 != undefined){
          this.chart3.dispose();
        }
        this.chart3 = echarts.init(chartDom);
        var option;
        option = {
          title: {text: '用水趋势分析'},
          tooltip: {trigger: 'axis', axisPointer: {type: 'shadow'}},
          legend: {data: ['自来水用水量','中水用水量']},
          toolbox: {
            feature: {
              dataView: {show: true, readOnly: false},
              magicType: {show: true, type: ['line', 'bar']},
              restore: {show: true},
              saveAsImage: {show: true}
            },
            padding: [0,15,0,0]
          },
          xAxis: {type: 'category', data: this.water1},
          yAxis: {type: 'value' },
          series: [
            {name: '自来水用水量', data: this.water2, stack: "Search Engine", type: 'bar'},
            {name: '中水用水量', data: this.recycled2, stack: "Search Engine", type: 'bar'},
            {
            name: '总计',
              type: 'line',
              lineStyle: {
                  opacity: 0,
              },
              symbolSize:0,
              data: addTwoArr(this.water2, this.recycled2)
            }
          ],
        };
        option && this.chart3.setOption(option,true);
      },
    },
    created () {
      this.handleChange1();
      this.loadWaterAndRecycled();
      this.getWaterByDpet();
      this.getRecycledByDpet();
      setTimeout(() => {
        this.formInline.dept = this.dept[this.dept.length-1].departName;
        this.loadWater();
      }, 500)
      setTimeout(() => {
        
      }, 700)
    },
    mounted(){
      //this.datasource = data
      setTimeout(() => {
        this.thisMonth = this.thisMonthWater + this.thisMonthRecycled;
        if(!this.thisMonth){
          this.thisMonth = 0;
        }
        this.yearAvg = this.yearAvgWater + this.yearAvgRecycled;
        this.yearMax = Math.max.apply(null,addTwoArr(this.water2, this.recycled2));
        this.yearMin = Math.min.apply(null,addTwoArr(this.water2, this.recycled2));
        this.getzhu();
        this.getbing();
        this.getzhe();
      }, 900)
    },
  }
</script>

<style>
 .sousuo{
  font-size: 14px;
  display: inline;
  /* font-weight:bold; */
 }
 .five {
  width: 100%;
  height: 100%;
}
.el-card__body{
    padding-top: 5px;
    padding-left: 20px;
    padding-right: 20px;
    padding-bottom: 30px;
  }
</style>
  
  
  